package com.dy.controller;

import com.dy.domain.User;
import com.dy.service.UserService;
import com.dy.utils.Code;
import com.dy.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    //自动装配userService
    @Autowired
    private UserService userService;

    /**
     * 添加user的请求
     *
     * @return Result型封装的json
     */
    @PostMapping
    public Result add(@RequestBody User user) {
        boolean flag = userService.add(user);
        Integer code = flag ? Code.DELETE_OK : Code.DELETE_ERR;
        String msg = flag ? "数据添加成功" : "数据添加失败，请重试！";
        return new Result(code, flag, msg);
    }

    /**
     * 更新user信息的请求
     *
     * @return Result型封装的json
     */
    @PutMapping
    public Result update(@RequestBody User user) {
        boolean flag = userService.update(user);
        Integer code = flag ? Code.DELETE_OK : Code.DELETE_ERR;
        String msg = flag ? "数据更新成功" : "数据更新失败，请重试！";
        return new Result(code, flag, msg);
    }

    /**
     * 根据id删除user的请求
     *
     * @return Result型封装的json
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean flag = userService.deleteById(id);
        Integer code = flag ? Code.DELETE_OK : Code.DELETE_ERR;
        String msg = flag ? "数据删除成功" : "数据删除失败，请重试！";
        return new Result(code, flag, msg);
    }

    /**
     * 根据id查询信息的请求
     *
     * @return Result型封装的json
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        User user = userService.getById(id);
        Integer code = user != null ? Code.GET_OK : Code.GET_ERR;
        String msg = user != null ? "数据查询成功" : "数据查询失败，请重试！";
        return new Result(code, user, msg);
    }

    /**
     * 查询所有的请求
     *
     * @return Result型封装的json
     */
    @GetMapping
    public Result getAll() {
        List<User> users = userService.getAll();
        Integer code = users != null ? Code.GET_OK : Code.GET_ERR;
        String msg = users != null ? "数据查询成功" : "数据查询失败，请重试！";
        return new Result(code, users, msg);
    }

}
